package com.yanfan.modbus.frame.abs;


import com.yanfan.modbus.ModbusUtils;
import com.yanfan.modbus.exception.ModbusTransportException;
import io.netty.buffer.ByteBuf;

/**
 * <p>Abstract ReadNumericRequest class.</p>
 *
 * @author Matthew Lohbihler
 * @version 5.0.0
 */
abstract public class ReadNumericRequest extends ModbusRequest {
    private int startOffset;
    private int numberOfRegisters;


    public ReadNumericRequest(int slaveId, int startOffset, int numberOfRegisters) throws ModbusTransportException {
        super(slaveId);
        this.startOffset = startOffset;
        this.numberOfRegisters = numberOfRegisters;
    }

    public ReadNumericRequest(int slaveId) throws ModbusTransportException {
        super(slaveId);
    }


    @Override
    public void validate() throws ModbusTransportException {
        ModbusUtils.validateOffset(startOffset);
        ModbusUtils.validateNumberOfRegisters(numberOfRegisters);
        ModbusUtils.validateEndOffset(startOffset + numberOfRegisters - 1);
    }


    /**
     * {@inheritDoc}
     */
    @Override
    protected void writeRequest(ByteBuf buf) {
        buf.writeShort(startOffset);
        buf.writeShort(numberOfRegisters);
    }


    @Override
    protected void readRequest(ByteBuf buf) {
        startOffset = buf.readUnsignedShort();
        numberOfRegisters = buf.readUnsignedShort();
    }


    @Override
    public String toString() {
        return "startOffset=" + startOffset + ", numberOfRegisters=" + numberOfRegisters;
    }
}
